/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package bpmlab.shift.config;

import bpmlab.shift.dao.DAOFactory;
import bpmlab.shift.dao.JpaUtil;
import bpmlab.shift.dao.service.UsuarioDAO;
import bpmlab.shift.entity.Papel;
import bpmlab.shift.entity.Usuario;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 *
 * @author bpmlab
 */
public class Autenticacao implements UserDetailsService {

    private static final Logger LOG = Logger.getLogger(Autenticacao.class.getName());
    private final UsuarioDAO daoU = DAOFactory.criarUsuarioDAO();

    @Override
    public UserDetails loadUserByUsername(String string) throws UsernameNotFoundException, DataAccessException {
        LOG.log(Level.INFO, string);
        if (string == null || string.isEmpty()) {
            throw new UsernameNotFoundException(string);
        }

        Usuario usuarioLogado;
        try {
            usuarioLogado = daoU.obterPorLogin(string);
        } catch (Exception e) {
            throw new UsernameNotFoundException(string, e);
        }

        List<GrantedAuthority> papeis = new ArrayList<>();
        
        for (Papel papel : usuarioLogado.getPapeis()) {
            papeis.add(new GrantedAuthorityImpl(papel.getNome()));
        }
        
        JpaUtil.closeEntityManager();
        return new User(usuarioLogado.getLogin(),
                usuarioLogado.getSenha(),
                true,
                true,
                true,
                true,
                papeis);
    }

}
